package com.ubxtech.rocketmq.config;

import com.ubxtech.rocketmq.properties.RocketMqConfigProperties;
import org.apache.rocketmq.spring.support.DefaultRocketMQListenerContainer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.StringUtils;

/**
 * @author Victor.Xiao
 * @since 2023-11-28 20:02
 **/
public class IsolationConfig implements BeanPostProcessor {
    private RocketMqConfigProperties rocketMqConfigProperties;

    public IsolationConfig(RocketMqConfigProperties rocketMqConfigProperties) {
        this.rocketMqConfigProperties = rocketMqConfigProperties;
    }

    /**
     * 根据环境重新隔离topic
     * @author Victor.Xiao
     * @since 2023-11-29 10:35
    */
    @Override
    public Object postProcessBeforeInitialization(@SuppressWarnings("NullableProblems") Object bean, String beanName) throws BeansException {
        if(bean instanceof DefaultRocketMQListenerContainer){

            DefaultRocketMQListenerContainer container = (DefaultRocketMQListenerContainer) bean;

            if ("1".equalsIgnoreCase(rocketMqConfigProperties.getEnvIsolationFlag()) ) {
                String topic = container.getTopic();
                //消费组也要改
                String group = container.getConsumerGroup();
                if (StringUtils.hasText(rocketMqConfigProperties.getRegion())) {
                    topic = String.join("_", topic, rocketMqConfigProperties.getRegion());
                    group = String.join("_", group, rocketMqConfigProperties.getRegion());
                }
                if (StringUtils.hasText(rocketMqConfigProperties.getEnvironment())) {
                    topic = String.join("_", topic, rocketMqConfigProperties.getEnvironment());
                    group = String.join("_", group, rocketMqConfigProperties.getEnvironment());
                }
                container.setTopic(topic);
                container.setConsumerGroup(group);
            }

            return container;
        }
        return bean;
    }
}
